package com.summba.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Common {
	
	public static final Logger summbaLogger = Logger.getLogger(Common.class);
	public static List <String> acList;
	public static int iCount = 0;
	
	public static BufferedReader getFileInfo(String strPath){
		BufferedReader fileBR = null;
		try{
			FileInputStream file = new FileInputStream(strPath);
	        InputStreamReader fileR = new InputStreamReader(file,"utf-8");
	        fileBR = new BufferedReader(fileR);
		}catch(Exception e){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();
		}
		return fileBR;
	}
	
	public static List <String> bufferedReaderToList( BufferedReader inStrm ){
		List <String> strList = new ArrayList <String>();
		try{
			BufferedReader tempStrm = inStrm;
			String temp = "";
            while((temp = tempStrm.readLine()) != null){
            	//summbaLogger.info("temp :"+temp);
            	strList.add(temp);
            	//summbaLogger.info("temp : |"+temp); 
            }
		}catch( Exception e){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();	
		}
		return strList;
	}
	
	/**
	 * @author Mark Liang
	 * @param File  | This param is a file path
	 * @param content | This param is write to file string
	 * 
	 */
	public static void appendFile( String file ,String content ){
		try{
			//String File = "";
			OutputStreamWriter out;
			out = new OutputStreamWriter( new FileOutputStream(file,true),"utf-8");
			out.write( content );
			out.flush();
			out.close();
		}catch( Exception e){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();
		}
	}
	
	public static void appendFile(String file , Set<String> setContainer ){
		try{
			OutputStreamWriter out;
			out = new OutputStreamWriter(new FileOutputStream(file,true),"utf-8");
			String object = "" ;
			for (Iterator<String> iterator = setContainer.iterator(); iterator
					.hasNext();) {
				object += (String) iterator.next() + "\n";
			}
			out.write( object );
			out.flush();
			out.close();
		}catch( Exception e){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();
		}
		
	}
	
	public static void writeFile( String File ,String content ){
		try{
			//String File = "";
			OutputStreamWriter out;
			out = new OutputStreamWriter( new FileOutputStream(File,false),"utf-8");
			out.write( content );
			out.flush();
			out.close();
		}catch( Exception e){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();
		}
	}
	
	public static void writeFile( String File ,BufferedReader br ){
		try{
			//String File = "";
			BufferedWriter bw = new BufferedWriter (new FileWriter( File , true));
			String temp = "";
			while((temp = br.readLine()) != null){
				bw.write(temp+"\n");
			}
			bw.flush();
			bw.close();
		}catch( Exception e){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();
		}
	}
	
	
	public static String getBatchID(){
		long begin = System.currentTimeMillis(); 
		String temp = String.valueOf(begin);
		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");   
		Date currentTime = new Date();//�1�7�0�1�1�7�1�7�1�7�0�2�0�3�0�1�0�2�1�7�1�7   
		String timeStr_1 = formatter.format(currentTime)+
		temp.substring(temp.length()-3, temp.length()); //�1�7�1�7�1�7�1�7�1�7�1�7�0�2�1�7�1�7�1�7�0�4�1�7�1�7   
		//long end = System.currentTimeMillis();   
		//System.out.println("[1] " + timeStr_1 );
		return timeStr_1;
	}
		
	public static String getTagData( String Data,String tag ){
		String strData = "";
		try{
			String temp = Data;
			//String temp2 = null;
			//int inTagLen = tag.length();
			String strKeyword1 = "<"+tag+">";
			String strKeyword2 = "</"+tag+">";
			int beginIndex = temp.indexOf(strKeyword1) + strKeyword1.length();
			//summbaLogger.info("beginIndex : "+beginIndex);
			//summbaLogger.info("temp1 : "+temp1);	
			temp = temp.substring(beginIndex);
			int endIndex = temp.indexOf(strKeyword2);
			///summbaLogger.info("endIndex : "+endIndex);
			temp = temp.substring(0, endIndex);
			strData = temp;
			summbaLogger.info( tag+" : "+strData);
		}catch( Exception e ){
			summbaLogger.info("Error Message : "+e.getMessage()+
					"| Error Stack Trace is :"+e.getStackTrace()); 
			e.printStackTrace();
		}
		return strData;
	}
	
	public static byte[] intToByteArray(int value) {
        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
	}
	
	public static byte[] charToByteArray(char value) {
        return new byte[] {
                (byte)(value >>> 8),
                (byte)value};
	}
	
	public static char ByteArrayToChar( byte[] value){
		return (char)(value[1] | value[0] << 8);
		
	}
	
	public static int ByteArrayToInt( byte[] value ){
		//return (int)(value[0] | value[1] << 8 | value[2] << 16 | value[3] << 24);
		//return (int)(value[3] 0xff | value[2] << 8 | value[1] << 16 | value[0] << 24);
		int targets = (value[3] & 0xff) | ((value[2] << 8) & 0xff00) // | �1�7�1�7�0�5�1�7�1�7�˄1�7�1�7
		| ((value[1] << 24) >>> 8) | (value[0] << 24); 
		return targets;
	}
	
	public static int ByteArrayToInt2( byte[] value ){
		//return (int)(value[0] | value[1] << 8 | value[2] << 16 | value[3] << 24);
		return (int)(value[3]  | value[2] << 8 | value[1] << 16 | value[0] << 24);
		//int targets = (value[3] & 0xff) | ((value[2] << 8) & 0xff00) // | �1�7�1�7�0�5�1�7�1�7�˄1�7�1�7
		//| ((value[1] << 24) >>> 8) | (value[0] << 24); 
		//return targets;
		/*
		int result = 0;
	    for (int i=0; i<4; i++) {
	      result = ( result << 8 ) - Byte.MIN_VALUE + (int) value[i];
	    }
	    return result;
		*/
	}
	
	public static short ByteArrayToShort( byte[] value ){
		return (short)( value[1] | value[0] << 8);
	}
	
	public static byte[] shortToByteArray( short value ){
		return new byte[] {
                (byte)(value >>> 8),
                (byte)value};
	}
	
	/**
	 * @author Mark Liang
	 * @param 
	 * @return
	 **/
	public static List<String> xpathParseXML(String classPath,String xPath,
			int returnType ) throws Exception{
		List<String> reList = new ArrayList <String>();
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(true); // never forget this!
	    DocumentBuilder builder = domFactory.newDocumentBuilder();
		XPath xpath = XPathFactory.newInstance().newXPath();
		InputSource inputSource = new InputSource(classPath);
	    Document doc = builder.parse(inputSource);
		if( returnType == 1 ){
			NodeList nodesList = (NodeList) xpath.evaluate(xPath, 
		    		doc, XPathConstants.NODESET);
		    for (int i = 0; i < nodesList.getLength(); i++) {
		    	//System.out.println("nodesL1Class :" + 
		    			//nodesL1Class.item(i).getTextContent());
		    	String tempKeyword = nodesList.item(i).getTextContent();
		    	reList.add(tempKeyword);
			}
		}
		return reList;
	}
	
	/**
	 * @author Mark Liang
	 * @param Stirng FilePath
	 * @return true or false
	 */
	public static boolean checkFileExistAndCreate( String FilePath){
		try{
			File tempFile = new File(FilePath);
			if( !tempFile.exists() ){
				tempFile.createNewFile();
			}
			return true;
		}catch(IOException e){
			e.printStackTrace();
			return false;
		}
	}
	
	public static List<String> getFloderFileList(String p){
		List<String> refileList = new ArrayList<String>();
		File path = new File(p); 
		String[] fileList = path.list();
		for (int i = 0; i < fileList.length; i++) {
			String string = p + File.separatorChar + fileList[i];
			refileList.add(string);
		}
		return refileList;
	}
	
	public static List<String> getFloderAllFileList( String p ,boolean subFolderFlag ){
		List<String> refileList = new ArrayList<String>();
		File file = new File(p);
		if(file.exists()){
			File files[] = file.listFiles();
			if(subFolderFlag){
				for(int i = 0; i < files.length; i++){
					if(files[i].isFile()){
						refileList.add( p + File.separatorChar + files[i].getName());
					}
					else if(files[i].isDirectory()){
						refileList.addAll( getFloderAllFileList(p + File.separatorChar + files[i].getName(), subFolderFlag));
					}
				}
			}
			else{
				for(int i = 0; i < files.length; i++){
					if(files[i].isFile()){
						refileList.add(p + File.separatorChar + files[i].getName());
					}
				}
				
			}
		}
		return refileList;
	}
	
	
}